import { showToast } from "../../utils/asyncWx.js"
import { request } from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  data: {
    query: '',
    // 搜索出来的商品列表
    goods: [],
    isFocus: false,
    // 控制输入框的内容
    inpValue: ''
  },
  // 防抖定时器，要设置为全局，不然会重复打开同名定时器
  timer: null,
  onLoad: function (options) {

  },
  // 取消按钮点击事件
  async handleSearchCancel () {
    this.setData({
      isFocus: false,
      goods: [],
      inpValue: ''

    })
    clearTimeout(this.timer)
  },
  // 输入时触发事件
  handleInput (e) {
    // 显示取消按钮
    this.setData({
      isFocus: true
    })
    const { value: query } = e.detail
    //当清空时，隐藏取消按钮,清空数组
    if (query.trim().length == 0) {
      this.setData({
        isFocus: false,
        query: '',
        goods: []
      })
      clearTimeout(this.timer)
      return
    }
    // 设置定时器防抖
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      this.qsearch(query.trim())
    }, 1500)

  },
  //发送请求
  async qsearch (query) {
    if (query.length !== 0) {
      const res = await request({
        url: '/goods/search',
        method: 'GET',
        data: {
          query,
        }
      })
      let goods = []
      //过滤一下属性
      res.goods.forEach(item => {
        goods.push({
          goods_id: item.goods_id,
          goods_name: item.goods_name
        })
      });
      this.setData({
        goods

      })
    }
    else {
      return showToast({ title: "请输入关键字", icon: "none" })
    }
  }


})